/*防抖方法*/

(function (window) {
  function debounce(fn, imgArr, event, delay) {
    var delay = delay || 300;
    var timer = null;
    return function (e) {
      timer && clearTimeout(timer);
      timer = setTimeout(() => {
        fn(imgArr);
      }, delay);
    };
  }

  // 1. 图片的按需加载
  // var lazyLoadClass = '.lazyload-img';
  // var imgArr = Array.prototype.slice.call(document.querySelectorAll(lazyLoadClass));
  // const imgArr = Array.from(document.querySelectorAll(lazyLoadClass));
  const lazyLoadClass = '.lazyload-img';
  function loadImage(selector) {
    const imgArr = Array.from(selector.querySelectorAll(lazyLoadClass));
    window.addEventListener('scroll', debounce(lazyLoadImgs, imgArr), false);
    lazyLoadImgs(imgArr);
  }

  function lazyLoadImgs(imgArr) {
    // var imgArr = Array.prototype.slice.call(document.querySelectorAll(lazyLoadClass));
    for (var i = 0; i < imgArr.length; i++) {
      if (isInVisibleArea(imgArr[i])) {
        imgArr[i].src = imgArr[i].getAttribute('data-src');
        imgArr[i].removeAttribute('data-src');
        imgArr[i].classList.remove('lazyload-img');
        imgArr.splice(i, 1);
        i--;
      }
    }
  }
  window.loadImage = loadImage;

  // 是否在页面可视区内
  function isInVisibleArea(el) {
    var rect = el.getBoundingClientRect();
    return (
      rect.bottom > 0 &&
      rect.top < window.innerHeight &&
      rect.right > 0 &&
      rect.left < window.innerWidth
    );
  }
})(window);
